package com.live.http.slider;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Connection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class GetLocation implements Runnable{

	private ListPageChannel channel;

	public GetLocation(ListPageChannel channel) {
		this.channel = channel;
	}
	
	public void run(){
		try {
			putListPagesToChannel();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取<code>Constants.START_PAGE</code>到<code>Constants.END_PAGE</code>
	 * 页的所有链接地址
	 * 
	 * @return
	 */
	public void putListPagesToChannel() throws Exception {
		String listUrl;// = Constants.URL_REPLACE;
		ListPage listPage;
		for (int i = Constants.START_PAGE; i < Constants.END_PAGE; i++) {
			listUrl = executeListPageUrl(i);
			listPage = getListPage(i, listUrl);
			channel.addListPage(listPage);
		}
		
	}

	/**
	 * 获取链接列表的页面
	 * 
	 * @param pageId
	 * @param listUrl
	 * @return
	 * @throws Exception
	 */
	public ListPage getListPage(int pageId, String listUrl) throws Exception {
		Connection conn = ConnectionFactory.getConnection(listUrl, 5000);
		Document doc = conn.get();
		Elements elements;
		elements = doc.select("div[class=list] a");
//		elements=doc.getElementsByClass("list");
		List<Page> pages = new ArrayList<Page>();

		String name;
		String url;
		for (Element element : elements) {
			name = element.text();
			url = element.attr("href");
			url = executePageUrl(url);
			pages.add(new Page(name, url));
		}

		return new ListPage(pages, pageId);
	}

	/**
	 * 处理某个页面链接地址
	 * 
	 * @param pageUrl
	 * @return
	 */
	private String executePageUrl(String pageUrl) {
		return Constants.BASE_URL+pageUrl;
	}

	/**
	 * 处理链接列表页面的地址
	 * 
	 * @param listPageUrl
	 * @return
	 */
	private String executeListPageUrl(int pageId) {
		return Constants.URL_REPLACE.replaceAll("#page#", String.valueOf(pageId));
	}
}
